package com.xiaofeng.auth.domain.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import com.xiaofeng.auth.common.enums.AuthUserStatusEnum;
import com.xiaofeng.auth.common.enums.IsDeletedFlagEnum;
import com.xiaofeng.auth.domain.constants.AuthConstants;
import com.xiaofeng.auth.domain.convert.AuthRoleBOConverter;
import com.xiaofeng.auth.domain.convert.AuthUserBOConverter;
import com.xiaofeng.auth.domain.entity.AuthUserBO;
import com.xiaofeng.auth.domain.redis.RedisUtil;
import com.xiaofeng.auth.domain.service.AuthUserDomainService;
import com.xiaofeng.subject.infra.basic.entity.*;
import com.xiaofeng.subject.infra.basic.service.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: chc
 * @Date: 2024/02/17/21:52
 * @Description:
 */
@Service
public class AuthUserDomainServiceImpl implements AuthUserDomainService {

    @Resource
    private AuthUserService authUserService;

    @Resource
    private AuthPermissionService authPermissionService;

    @Resource
    private AuthUserRoleService authUserRoleService;

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    @Resource
    private AuthRoleService authRoleService;

    @Resource
    private RedisUtil redisUtil;

    private String salt = "xiaofeng";

    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";

    private static final String LOGIN_PREFIX = "loginCode";

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public Boolean register(AuthUserBO authUserBO) {
        //校验用户是否存在
        AuthUser existAuthUser = new AuthUser();
        existAuthUser.setUserName(authUserBO.getUserName());
        List<AuthUser> existUser = authUserService.queryByCondition(existAuthUser);
        if (existUser.size() > 0) {
            return true;
        }
        AuthUser authUser = AuthUserBOConverter.INSTANCE.convertBOToEntity(authUserBO);
        if (StringUtils.isNoneBlank(authUser.getPassword())){
            authUser.setPassword(SaSecureUtil.md5BySalt(authUser.getPassword(),salt)); //密码加密算法(加盐加密)
        }
        authUser.setStatus(AuthUserStatusEnum.OPEN.getCode());
        authUser.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        Integer count = authUserService.insert(authUser); //插入到数据库
        //建立一个初步的角色关联
        AuthRole authRole = new AuthRole();
        authRole.setRoleKey(AuthConstants.NORMAL_USER);
        //查询角色表的数据
        AuthRole roleResult = authRoleService.queryByCondition(authRole);
        //获取角色id
        Long roleId = roleResult.getId();
        //获取用户id
        Long userId = authUser.getId();
        AuthUserRole authUserRole = new AuthUserRole();
        authUserRole.setUserId(userId);
        authUserRole.setRoleId(roleId);
        authUserRole.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        //保存用户角色关系表
        authUserRoleService.insert(authUserRole);
        //构建角色缓存关键字key
        String roleKey = redisUtil.buildKey(authRolePrefix, authUser.getUserName());
        List<AuthRole> roleList = new LinkedList<>();
        roleList.add(authRole);
        //将角色缓存到redis
        redisUtil.set(roleKey, new Gson().toJson(roleList));
        //创建角色权限实列对象
        AuthRolePermission authRolePermission = new AuthRolePermission();
        //设置角色id
        authRolePermission.setRoleId(roleId);
        //在角色权限表中通过角色id查询角色权限表
        List<AuthRolePermission> rolePermissionList = authRolePermissionService.
                queryByCondition(authRolePermission);
        //将查询到的角色权限数据循环遍历取出permissionId集合
        List<Long> permissionIdList = rolePermissionList.stream()
                .map(AuthRolePermission::getPermissionId).collect(Collectors.toList());
        //根据permissionId集合查询权限
        List<AuthPermission> permissionList = authPermissionService.queryByRoleList(permissionIdList);
        //构建权限缓存关键字key
        String permissionKey = redisUtil.buildKey(authPermissionPrefix, authUser.getUserName());
        //将查询到的权限数据缓存到redis中
        redisUtil.set(permissionKey, new Gson().toJson(permissionList));
        return count > 0;
    }

    @Override
    public Boolean update(AuthUserBO authUserBO) {
        //将AuthUserBO对象转换乘AuthUser对象
        AuthUser authUser = AuthUserBOConverter.INSTANCE.convertBOToEntity(authUserBO);
        Integer count = authUserService.update(authUser);
        return count > 0;
    }

    @Override
    public Boolean delete(AuthUserBO authUserBO) {
        AuthUser authUser = new AuthUser();
        authUser.setId(authUserBO.getId());
        authUser.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        Integer count = authUserService.update(authUser);
        return count > 0;
    }

    @Override
    public SaTokenInfo doLogin(String vailCode) {
        //构建验证码缓存关键Key
        String loginKey = redisUtil.buildKey(LOGIN_PREFIX, vailCode);
        //通过key查询缓存
        String openId = redisUtil.get(loginKey);
        if (StringUtils.isBlank(openId)) {
            return null;
        }
        AuthUserBO authUserBO = new AuthUserBO();
        authUserBO.setUserName(openId);
        //注册用户信息
        this.register(authUserBO);
        //sa-token登陆
        StpUtil.login(openId);
        //获取token信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo;
    }

    @Override
    public AuthUserBO getUserInfo(AuthUserBO authUserBO) {
        AuthUser authUser = new AuthUser();
        authUser.setUserName(authUserBO.getUserName());
        List<AuthUser> userList = authUserService.queryByCondition(authUser);
        if(CollectionUtils.isEmpty(userList)){
            return new AuthUserBO();
        }
        AuthUser user = userList.get(0);
        return AuthUserBOConverter.INSTANCE.convertEntityToBO(user);
    }
}
